﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

using AtletIS.Shared.Entities;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Data;
using System.IO;

namespace AtletIS.Shared.Helpers
{
    public static class PointsHelper
    {
        private static PerformancesTableAdapter taPerformances = new PerformancesTableAdapter();
        private static DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
        private static CategoriesTableAdapter taCategories = new CategoriesTableAdapter();

        /// <summary>
        ///  Oboduje NErozdelenú disciplínu
        /// </summary>
        public static void Simple(DisciplineListEntity discipline)
        {
            try
            {
                aDbDataSet.PerformancesDataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(discipline.ID);

                if (dtPerformances.Rows.Count > 0)
                    SetPoints(dtPerformances);
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        /// <summary>
        ///  Oboduje rozdelenú disciplínu
        /// </summary>
        public static void Multi(DisciplineListEntity discipline)
        {
            try
            {
                // Nacita body
                DataTable dtCategory = DatabaseHelper.GetCategoriesById(Globals.ActiveDiscipline.CategoryId); 
                string[] aPoints = dtCategory.Rows[0]["Points"].ToString().Split(',');

                DataTable dtChildren = DatabaseHelper.GetDisciplineListByParentIdActive(discipline.ID); 

                // Najlepší pretekári spolu v prvej disciplíne
                if (discipline.IsFinal)
                {
                    int index = 0;

                    foreach (DataRow drChild in dtChildren.Rows)
                    {
                        aDbDataSet.PerformancesDataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(drChild["ID"]));

                        #region Reset points

                        foreach (DataRow dr in dtPerformances)
                            dr["Points"] = 0.00;

                        taPerformances.Update(dtPerformances);

                        #endregion

                        #region Set points

                        DataRow[] aPerformances = dtPerformances.Select("PointsScoring = 1 AND Code = 0 AND Result > 0", "Code, Result");

                        for (int i = 0; i < aPerformances.Count(); i++)
                        {
                            // Pretekar este nema body
                            if (i < aPoints.Length && Convert.ToInt32(aPerformances[i]["Points"]) == 0)
                            {
                                DataRow[] aEqualPerformances = dtPerformances.Select(string.Format("PointsScoring = 1 AND Result = {0}", aPerformances[i]["Result"]));
                                if (aEqualPerformances != null && aEqualPerformances.Count() > 1)
                                {
                                    double body = 0;
                                    for (int riadok = i; riadok < i + aEqualPerformances.Count(); riadok++)
                                    {
                                        body += Convert.ToInt32(aPoints[riadok]);
                                    }
                                    body = Math.Round(body / aEqualPerformances.Count(), 2);

                                    foreach (var equalPerf in aEqualPerformances)
                                    {
                                        equalPerf["Points"] = body;
                                        taPerformances.Update(equalPerf);
                                    }
                                }
                                else
                                {
                                    aPerformances[i]["Points"] = aPoints[i + index];
                                    taPerformances.Update(aPerformances[i]);
                                }
                            }

                            
                        }

                        index += aPerformances.Count();

                        #endregion
                    }
                }
                else // Najlepší pretekári oddelene
                {
                    #region Get performances

                    aDbDataSet.PerformancesDataTable dtSummaryPerformances = new aDbDataSet.PerformancesDataTable();

                    foreach (DataRow drChild in dtChildren.Rows)
                        dtSummaryPerformances.Merge(DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(drChild["ID"])));

                    #endregion

                    #region Reset points

                    foreach (DataRow dr in dtSummaryPerformances)
                        dr["Points"] = 0.00;

                    taPerformances.Update(dtSummaryPerformances);

                    #endregion

                    #region Set points

                    DataRow[] aPerformances = dtSummaryPerformances.Select("PointsScoring = 1 AND Code = 0 AND Result > 0", "Code, Result");

                    for (int i = 0; i < aPerformances.Count(); i++)
                    {
                        // Pretekar este nema body
                        if (i < aPoints.Length && Convert.ToInt32(aPerformances[i]["Points"]) == 0)
                        {
                            DataRow[] aEqualPerformances = dtSummaryPerformances.Select(string.Format("PointsScoring = 1 AND Result = {0}", aPerformances[i]["Result"]));
                            if (aEqualPerformances != null && aEqualPerformances.Count() > 1)
                            {
                                double body = 0;
                                for (int riadok = i; riadok < i + aEqualPerformances.Count(); riadok++)
                                {
                                    body += Convert.ToInt32(aPoints[riadok]);
                                }
                                body = Math.Round(body / aEqualPerformances.Count(), 2);

                                foreach (var equalPerf in aEqualPerformances)
                                {
                                    equalPerf["Points"] = body;
                                    taPerformances.Update(equalPerf);
                                }
                            }
                            else
                            {
                                aPerformances[i]["Points"] = aPoints[i];
                                taPerformances.Update(aPerformances[i]);
                            }
                        }
                    }

                    #endregion
                }
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Nepodarilo sa načítať bodovacie hodnoty.");
            }

        }

        private static void SetPoints(aDbDataSet.PerformancesDataTable dtPerformances)
        {
            // Reset points
            foreach (DataRow dr in dtPerformances)
            {
                dr["Points"] = 0.00;
            }
            taPerformances.Update(dtPerformances);

            // Zoradí [Performances]
            DataRow[] aPerformances = dtPerformances.Select("PointsScoring = 1 AND Code = 0 AND Rank > 0", "Code, Rank");

            DataTable dtCategory = DatabaseHelper.GetCategoriesById(Globals.ActiveDiscipline.CategoryId);
            if (dtCategory.Rows.Count > 0)
            {
                string[] aPoints = dtCategory.Rows[0]["Points"].ToString().Split(',');

                for (int i = 0; i < aPerformances.Count(); i++)
                {
                    // Pretekar este nema body
                    if (i < aPoints.Length && Convert.ToInt32(aPerformances[i]["Points"]) == 0)
                    {
                        DataRow[] aEqualPerformances = dtPerformances.Select(string.Format("Rank = {0}", aPerformances[i]["Rank"]));
                        if (aEqualPerformances != null && aEqualPerformances.Count() > 1)
                        {
                            double body = 0;
                            for (int riadok = i; riadok < i + aEqualPerformances.Count(); riadok++)
                            {
                                body += Convert.ToInt32(aPoints[riadok]);
                            }
                            body = Math.Round(body / aEqualPerformances.Count(), 2);

                            foreach (var equalPerf in aEqualPerformances)
                            {
                                equalPerf["Points"] = body;
                                taPerformances.Update(equalPerf);
                            }
                        }
                        else
                        {
                            aPerformances[i]["Points"] = aPoints[i];
                            taPerformances.Update(aPerformances[i]);
                        }
                    }
                }
            }
        }

        public static void GetPointsTable(DisciplineListEntity discipline, StreamWriter sw)
        {
            DataTable dtPoints = DatabaseHelper.GetPoints(discipline.ID);
            if (dtPoints != null && dtPoints.Rows.Count > 0)
            {
                sw.WriteLine("<hr>");
                sw.WriteLine("<table class=\"extra\">");

                sw.WriteLine("<tr>");
                sw.WriteLine("  <td width=\"20\"></td>");
                sw.WriteLine("  <td><b>Bodovanie po " + dtPoints.Rows[0]["NumberOfDisciplines"].ToString() + " disciplínach</td>");
                sw.WriteLine("  <td align=\"center\"></td>");
                sw.WriteLine("</tr>");

                foreach (DataRow dr in dtPoints.Rows)
                {
                    sw.WriteLine("<tr>");
                    sw.WriteLine("  <td width=\"20\"></td>");
                    sw.WriteLine("  <td>" + dr["ClubCountry"].ToString() + "</td>");
                    sw.WriteLine("  <td align=\"center\">" + dr["Points"].ToString() + "</td>");
                    sw.WriteLine("</tr>");
                }

                sw.WriteLine("</table>");
            }
        }
    
    }
}
